/**
 * * @param  {Number} delay  节流时间
 * * @param  {Boolean} noTrailing true 在节流过后不会执行
 * * @param  {Function} callback    回调函数
 * * @param  {Boolean} debounceMode true 关闭
 * @description doc https://github.com/niksy/throttle-debounce
 */
export default function(delay, noTrailing, callback, debounceMode) {
    var timeoutID;

    var lastExec = 0;

    if (typeof noTrailing !== 'boolean') {
        debounceMode = callback;
        callback = noTrailing;
        noTrailing = undefined;
    }

    function wrapper() {
        var self = this;
        var elapsed = Number(new Date()) - lastExec;
        var args = arguments;

        function exec() {
            lastExec = Number(new Date());
            callback.apply(self, args);
        }

        function clear() {
            timeoutID = undefined;
        }

        if (debounceMode && !timeoutID) {
            exec();
        }

        if (timeoutID) {
            clearTimeout(timeoutID);
        }

        if (debounceMode === undefined && elapsed > delay) {
            exec();
        } else if (noTrailing !== true) {
            timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
        }
    }

    wrapper.cancel = function() {
        clearTimeout(timeoutID);
    };

    return wrapper;
}
